<route>
    {
        meta: {
            layout: 'index',
            title:'施工方案管理'
        }
    }  
</route>
<template>
    <view>
        <div class="app-container">
            <a-row v-if="!selectedReport">
                <a-input-search v-model:value="searchKey" placeholder="请输入xx信息" enter-button="搜索"
                    style="width: 250px; margin-bottom: 10px;" @search="handleQuery()" />
                <a-button style="margin-left: 10px;" type="dashed" @click="reset">重置</a-button>
                <a-button type="primary" style="margin-left: auto; margin-bottom: 10px; width: 100px;" @click="openAdd">
                    <template #icon><plus-outlined /></template>新增
                </a-button>
            </a-row>
            <a-row v-if="selectedReport">
                <a-button type="primary" style="margin-left: auto; margin-bottom: 10px; margin-right: 10px; width: 100px;"
                    @click="returned()">返回</a-button>
            </a-row>
            <div v-if="!selectedReport">
                <!-- 施工方案列表 -->
                <a-table :dataSource="dataSource" :columns="columns" bordered :pagination="false">
                    <template #bodyCell="{ column, text, record }">
                        <template v-if="column.dataIndex === 'action'">
                            <div>
                                <span>
                                    <a-button type="link" @click="openDetail(record)">查看详细信息</a-button>
                                    <!-- <a-button type="link" @click="openWrite('修改')">编辑</a-button> -->
                                    <AntdZh><a-popconfirm title="确定删除该条记录 ?" @confirm="del(record.id)">
                                        <a-button type="link" danger>删除</a-button>
                                    </a-popconfirm></AntdZh>
                                </span>
                            </div>
                        </template>
                    </template>
                </a-table>
                <AntdZh>
                    <a-pagination v-model:current="query.pageNum" v-model:pageSize="query.pageSize" :total="total"
                        @change="getList" />
                </AntdZh>

                <!-- 新增弹窗 -->
                <AntdConfirmModal title="生成施工方案" ref="modalRef" width="600px" @confirm="submitInfo">
                    <a-form :model="params" name="basic" :label-col="{ span: 8 }">
                        <a-row>
                            <a-col :pull="2" :span="22">
                                <a-form-item label="选择已有井" name="wellId">
                                    <well-select style="width: 100%;" @confirm="getSelectWell"></well-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <!-- 上传井眼轨迹 -->
                        <div style="width: 418px; margin-left: 40px; margin-bottom: 20px;">
                            <a-upload withCredentials v-model:fileList="fileList" name="file" :before-upload="beforeUpload"
                                @remove="handleRemove" :maxCount="1">
                                <a-button style="width: 418px;">
                                    <upload-outlined />上传井眼轨迹
                                </a-button>
                            </a-upload>
                        </div>
                    </a-form>
                    <a-table :dataSource="schemeArray" :columns="wellSelectColumns" bordered :pagination="false">
                        <template #bodyCell="{ column, text, record }">
                            <template v-if="column.dataIndex === 'action'">
                                <div style="margin-right: 8px">
                                    <span>
                                        <a-button type="link" @click="openDetail(record)">查看详细信息</a-button>
                                    </span>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </AntdConfirmModal>
            </div>

            <!-- 工程报告详细信息 -->
            <view v-if="selectedReport && (selectAccident == true)">
                <AccidentDetail :reportId="selectedReport"></AccidentDetail>
            </view>
            <!-- 收集卡详细信息 -->
            <view v-if="selectedReport && (selectCard == true)">
                <card-unlock-detail :reportId="selectedReport"></card-unlock-detail>
            </view>
            <!-- 施工方案详细信息 -->
            <view v-if="selectedReport && (selectScheme == true)">
                <SchemeDetail :reportId="selectedReport"></SchemeDetail>
            </view>
        </div>
    </view>
</template>
<script setup>
import { UploadOutlined, PlusOutlined } from '@ant-design/icons-vue'
import SchemeDetail from './detail'
import WellSelect from '@/custom/well/components/WellSelect'
import AccidentDetail from '../accidentReport/detail'
import CardUnlockDetail from '../cardUnlocking/detail'
import { queryList, createSchemes, updateOne, deleteOne } from '@/api/salvage/planDesign'
import { queryList as accidentList } from "@/api/salvage/accidentAlert";
import { queryList as cardUnlockList } from "@/api/salvage/threadCard"
import { getFile, downloadFile, upFile} from "@/api/file/file.js";
import request from "@/utils/request";
import useApp from "@/hooks";
const { $, proxy } = useApp();
const modalRef = ref(null);
const total = ref(1)
const searchKey = ref();
const query = ref({ pageNum: 1, pageSize: 10, sortBy: 'id', searchKey: '', wellId: '' });
// const data = reactive({
//     form: {}
// });
// const { form } = toRefs(data);
const fileList = ref([]);
const file = ref();
const form = ref({
    file: null,
    bucketName: "importPre",
});
const selectedReport = ref(false)
const selectAccident = ref(false)
const selectCard = ref(false)
const selectScheme = ref(false)
const dataSource = ref([]);
const doSchemeData = ref()
const schemeArray = ref([])
const accidentData = ref()
const cardUnlockData = ref()
//定义表格配置列
const columns = [
    {
        title: '井名',
        dataIndex: 'wellId',
        key: 'wellId',
        width: '30%'
    },
    {
        title: '编辑日期',
        dataIndex: 'updatedTime',
        key: 'updatedTime',
        width: '30%'
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
    }
];
// 弹窗表格配置
const wellSelectColumns = [
    {
        title: '信息表',
        dataIndex: 'title',
        key: 'title',
        width: '50%'
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
    }
];
// 新增弹窗
function openAdd() {
    modalRef.value.openModal();
}
// 删除施工方案
const del = key => {
    console.log(key);
    deleteOne(key).then(res => {
        $.showToast({
            title: '删除成功',
            icon: 'success'
        })
        getList()
    })
}
// 获得已存在的井方案
function getSelectWell(e) {
    schemeArray.value = []
    let querySurvey = { order: "DESC", pageNum: 1, pageSize: 10, sortBy: "id", wellId: e };
    Promise.all([
        accidentList(querySurvey),
        cardUnlockList(querySurvey),
    ]).then((res) => {
        console.log('res', res);
        if (res[0].content.length == 0) {
            $.showToast({
                title: '无工程事故复杂快报信息',
                icon: 'warn'
            })
        } else {
            accidentData.value = res[0].content[0]
            accidentData.value.title = `${e}井的事故快报信息卡`
            schemeArray.value.push(accidentData.value)
        }
        if (res[1].content.length == 0) {
            $.showToast({
                title: '无穿心解卡现场信息',
                icon: 'warn'
            })
        } else {
            cardUnlockData.value = res[1].content[0]
            cardUnlockData.value.title = `${e}井的穿心解卡信息收集卡`
            schemeArray.value.push(cardUnlockData.value)
        }
        console.log('schemeArray.value', schemeArray.value);
    });
}
// 文件上传
const beforeUpload = (file) => {
    // 记录文件
    form.value.file = file;
    if (
        file.type !== "application/vnd.ms-excel" &&
        file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ) {
        $.showToast({
            title: "只支持上传excel文件",
            icon: "error",
        });
        return false;
    }
    return true;
    // 直接停止上传
    // return false;
};
// 移除文件
const handleRemove = (file) => {
    form.value.file = {};
};

// 提交(合成施工方案)
function submitInfo() {
    if (schemeArray.value.length !== 2) {
        $.showToast({
            title: '缺少关键信息表无法生成施工方案',
            icon: 'warn'
        })
    } else {
        doSchemeData.value = { ...accidentData.value, ...cardUnlockData.value }
        console.log('doSchemeData.value', doSchemeData.value);
        createSchemes(doSchemeData.value.wellId).then(res => {
            // localStorage.setItem("schemeId", res.id);
            // localStorage.setItem("wellId", res.wellId);
            console.log('createSchemes', res);
            updateOne(res.id, doSchemeData.value).then(e => {
                console.log('updateOne', e);
                $.showToast({
                    title: '方案新建成功',
                    icon: 'success'
                })
                // 井眼轨迹
                const formData = new FormData();
                formData.append("file", form.value.file);
                formData.append("wellId", doSchemeData.value.wellId);
                request.post("/well/survey/import", formData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                }).then((res) => {
                    console.log(res);
                    localStorage.setItem("fileId", res.id);
                    $.showToast({
                        title: "井眼轨迹上传成功",
                        icon: "success",
                    });
                });
                getList()
            })
            modalRef.value.closeModal();
        })
    }
}
// 打开详细面板
function openDetail(e) {
    console.log('openDetail', e);
    if (e.hasOwnProperty('title')) {
        if (e.title.includes("事故快报信息卡")) {
            selectAccident.value = true
            selectedReport.value = e.id
            console.log('selectedReport.value', selectedReport.value);
        } else if (e.title.includes("穿心解卡信息收集卡")) {
            selectCard.value = true
            selectedReport.value = e.id
        }
    } else {
        selectScheme.value = true
        selectedReport.value = e.id
    }
}
/** 查询报告列表 */
function getList() {
    queryList(query.value).then((response) => {
        console.log(response);
        dataSource.value = response.content;
        total.value = response.totalElements;
    });
}
getList();

/** 搜索按钮操作 */
function handleQuery() {
    query.value.searchKey = searchKey.value;
    getList();
}
/** 表单重置 */
function reset() {
    searchKey.value = '';
    query.value = { pageNum: 1, pageSize: 10, sortBy: 'id', searchKey: '', }
    getList();
}
// 返回
function returned() {
    selectedReport.value = false
    selectAccident.value = false
    selectCard.value = false
    selectScheme.value = false
}
</script>